package com.heima.user.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserFollowDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.UserFanMapper;
import com.heima.user.mapper.UserFollowMapper;
import com.heima.user.service.UserFollowService;
import com.heima.utils.common.APUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;

@Service
@Slf4j
public class UserFollowServiceImpl implements UserFollowService {

    @Autowired
    private UserFollowMapper userFollowMapper;
    @Autowired
    private UserFanMapper userFanMapper;
    @Autowired
    private ApUserMapper apUserMapper;
    @Override
    @Transactional
    public ResponseResult userFollow(UserFollowDto dto) {
        if (dto == null){
            log.info("传入的数据为空");
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //获取用户id
        Integer userId = APUserThreadLocalUtil.getUser();
        //用户是否登录
        if (userId == null){
            log.info("用户id为空");
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查询用户的昵称
        ApUser user = apUserMapper.selectById(userId);
        String userName = user.getName();

        ApUserFan userFan = new ApUserFan();
        userFan.setUserId(dto.getAuthorId());
        userFan.setFansId(userId);
        userFan.setFansName(userName);
        userFan.setLevel(0);
        userFan.setCreatedTime(LocalDate.now());
        userFan.setIsDisplay(0);
        userFan.setIsShieldLetter(0);
        userFan.setIsShieldComment(0);

        ApUserFollow userFollow = new ApUserFollow();
        userFollow.setUserId(userId);
        userFollow.setFollowId(dto.getAuthorId());
        userFollow.setFollowName(userName);
        userFollow.setLevel(0);
        userFollow.setIsNotice(1);
        userFollow.setCreatedTime(LocalDate.now());
        //判断是否是关注
        if (dto.getOperation() == 0){
            //用户粉丝表中加入粉丝
            userFanMapper.insert(userFan);
            //用户关注信息表中加入已关注的用户
            userFollowMapper.insert(userFollow);
        }else {
            userFanMapper.deleteById(userId);
            userFollowMapper.deleteById(dto.getAuthorId());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



}
